package com.inhim.pjhim.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.inhim.pjhim.R;
import com.inhim.pjhim.dowloadfile.download.MyBusinessInfoDid;
import com.inhim.pjhim.entity.DownloadAuthor;
import com.inhim.pjhim.entity.ReaderInfo;
import com.inhim.pjhim.utils.ImageLoaderUtils;
import com.inhim.pjhim.utils.TextViewUils;
import com.inhim.pjhim.view.CircleImageView;
import com.inhim.pjhim.view.MyWebView;


/**
 * Created by hsmacmini on 2018/4/16.
 */

public class JIangyiFragment extends Fragment {
    private MyWebView mWebView;
    String content;
    final String mimeType = "text/html";
    final String encoding = "UTF-8";
    private RefreshReceiver refreshReceiver;
    private ReaderInfo.Reader readerInfo;
    private MyBusinessInfoDid businessInfoDid;
    private TextView textview1, textview2, textview3, textview4, textview6, textview;
    private String description;
    private TextView tv_author_name, tv_author_pastor, tv_author_from, tv_author_content;
    private CircleImageView iv_author_photo;
    //private MyScrollViewNew mScrollView;
    private Context mContext;
    private LinearLayout mScrollContainer;
    private ConstraintLayout in_author, constran_content;
    private DownloadAuthor mmDownloadAuthor;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_jiangyi, null);
        mContext = getActivity();
        content = getArguments().getString("content");
        readerInfo = (ReaderInfo.Reader) getArguments().getSerializable("result");
        businessInfoDid = (MyBusinessInfoDid) getArguments().getSerializable("businessInfoDid");
        mmDownloadAuthor= (DownloadAuthor) getArguments().getSerializable("DownloadAuthor");
        initView(view);
        IntentFilter filter = new IntentFilter();
        filter.addAction("refresh.fragment.content");
        //注册广播接收
        refreshReceiver = new RefreshReceiver();
        if (getActivity() != null) {
            getActivity().registerReceiver(refreshReceiver, filter);
        }
        return view;

    }

    private int mAuthorHeight, mConstranContentHeight;

    private void initView(View view) {
        in_author = view.findViewById(R.id.in_author);
        constran_content = view.findViewById(R.id.constran_content);
       /* in_author.post(new Runnable() {
            @Override
            public void run() {
                mAuthorHeight = in_author.getHeight();
            }
        });*/
        constran_content.post(new Runnable() {
            @Override
            public void run() {
                mConstranContentHeight = constran_content.getHeight();
            }
        });
        mScrollContainer = view.findViewById(R.id.constran);
        /*mScrollView = view.findViewById(R.id.my_scrollview);
        mScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView nestedScrollView, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                //mScrollView.setIsRecLayoutShow(UiUtil.isViewShowReally(mBottomListLayout));
            }
        });*/
        tv_author_name = view.findViewById(R.id.tv_author_name);
        tv_author_pastor = view.findViewById(R.id.tv_author_pastor);
        tv_author_from = view.findViewById(R.id.tv_author_from);
        tv_author_content = view.findViewById(R.id.tv_author_content);
        iv_author_photo = view.findViewById(R.id.iv_author_photo);
        textview = view.findViewById(R.id.textview);
        textview1 = view.findViewById(R.id.textview1);
        textview2 = view.findViewById(R.id.textview2);
        textview3 = view.findViewById(R.id.textview3);
        textview4 = view.findViewById(R.id.textview4);
        textview6 = view.findViewById(R.id.textview6);
        mWebView = view.findViewById(R.id.webView1);
        mWebView.getSettings().setJavaScriptEnabled(true);
        //设置 缓存模式
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        // 开启 DOM storage API 功能
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        mWebView.setVerticalScrollBarEnabled(false);

        mWebView.setVerticalScrollbarOverlay(false);

        mWebView.setHorizontalScrollBarEnabled(false);

        mWebView.setHorizontalScrollbarOverlay(false);
        if (content == null || content.length() == 0) {
            content = "暂无内容";
        }
        mWebView.loadDataWithBaseURL(null, content, mimeType, encoding, null);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        // 监听网页是否滑到底
        mWebView.setOnOverScrollListener(new MyWebView.OnOverScrollListener() {
            @Override
            public void onOverScrolled(MyWebView v, boolean onBottom) {
                //mScrollView.setIsWebViewOnBottom(onBottom);
            }
        });
        mWebView.setWebViewClient(mClient);
        if (businessInfoDid != null) {
            textview1.setText(businessInfoDid.getTitle());
            if (businessInfoDid.getReaderTypeText() != null) {
                textview2.setText("分类：" + businessInfoDid.getReaderTypeText());
            }
            textview3.setText(String.valueOf(businessInfoDid.getReadAmount()));
            textview4.setText(businessInfoDid.getTimeText());
            description = businessInfoDid.getSynopsis();
            if (description != null && !"".equals(description)) {
                textview.setVisibility(View.VISIBLE);
                textview.setText(description);
            }
            /*if (mmDownloadAuthor != null) {
                in_author.setVisibility(View.VISIBLE);
                textview6.setText("作者：" + mmDownloadAuthor.getName());
                TextViewUils.setText(tv_author_name, mmDownloadAuthor.getName());
                if(!"".equals(mmDownloadAuthor.getIdentity())){
                    tv_author_pastor.setVisibility(View.VISIBLE);
                    TextViewUils.setText(tv_author_pastor, mmDownloadAuthor.getIdentity());
                }
                TextViewUils.setText(tv_author_from, "来自:" + mmDownloadAuthor.getArea());
                TextViewUils.setText(tv_author_content, mmDownloadAuthor.getSynopsis());
                ImageLoaderUtils.setImage(mmDownloadAuthor.getHeadPortrait(), iv_author_photo);
            }else {
                in_author.setVisibility(View.GONE);
            }*/
        } else if (readerInfo != null) {
            textview1.setText(readerInfo.getTitle());
            if (readerInfo.getReaderTypeText() != null) {
                textview2.setText("分类：" + readerInfo.getReaderTypeText());
            }
            if (null != readerInfo.getAuthor()) {
                textview6.setText("作者：" + readerInfo.getAuthor().getName());
            }
            textview3.setText(String.valueOf(readerInfo.getReadAmount()));
            textview4.setText(readerInfo.getTimeText());
            description = readerInfo.getSynopsis();
            if (description != null && !"".equals(description)) {
                textview.setVisibility(View.VISIBLE);
                textview.setText(description);
            }
        }
        /*if (readerInfo != null && readerInfo.getAuthor() != null) {
            in_author.setVisibility(View.VISIBLE);
            TextViewUils.setText(tv_author_name, readerInfo.getAuthor().getName());
            if(!"".equals(readerInfo.getAuthor().getIdentity())){
                tv_author_pastor.setVisibility(View.VISIBLE);
                TextViewUils.setText(tv_author_pastor, readerInfo.getAuthor().getIdentity());
            }
            TextViewUils.setText(tv_author_from, "来自:" + readerInfo.getAuthor().getArea());
            TextViewUils.setText(tv_author_content, readerInfo.getAuthor().getSynopsis());
            ImageLoaderUtils.setImage(readerInfo.getAuthor().getHeadPortrait(), iv_author_photo);
        }else{
            in_author.setVisibility(View.GONE);
        }*/
    }
    private Mobile mobile;
    private WebViewClient mClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            mobile=new Mobile();
            mWebView.addJavascriptInterface(mobile, "mobile");
            mWebView.setOnContentChangeListener(() -> {
                if(mobile!=null){
                    mobile.onGetWebContentHeight();
                }
            });
            mobile.onGetWebContentHeight();
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(refreshReceiver);
    }

    public void setContext(String contents,ReaderInfo.Reader readerInfos ){
        content = contents;
        readerInfo = readerInfos;
        textview1.setText(readerInfo.getTitle());
        if (readerInfo.getReaderTypeText() != null) {
            textview2.setText("分类：" + readerInfo.getReaderTypeText());
        }
        /*if (null != readerInfo.getAuthor()) {
            in_author.setVisibility(View.VISIBLE);
            textview6.setText("作者：" + readerInfo.getAuthor().getName());
        }else{
            in_author.setVisibility(View.GONE);
        }*/
        textview3.setText(String.valueOf(readerInfo.getReadAmount()));
        textview4.setText(readerInfo.getTimeText());
        if (content == null || content.length() == 0) {
            content = "暂无内容";
        }
        mWebView.loadDataWithBaseURL(null, content, mimeType, encoding, null);
        mWebView.setWebViewClient(mClient);
    }

    class RefreshReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            content = intent.getStringExtra("content");
            readerInfo = (ReaderInfo.Reader) intent.getSerializableExtra("result");
            textview1.setText(readerInfo.getTitle());
            if (readerInfo.getReaderTypeText() != null) {
                textview2.setText("分类：" + readerInfo.getReaderTypeText());
            }
            if (null != readerInfo.getAuthor()) {
                textview6.setText("作者：" + readerInfo.getAuthor());
            }
            textview3.setText(String.valueOf(readerInfo.getReadAmount()));
            textview4.setText(readerInfo.getTimeText());
            if (content == null || content.length() == 0) {
                content = "暂无内容";
            }
            mWebView.loadDataWithBaseURL(null, content, mimeType, encoding, null);
            mWebView.setWebViewClient(mClient);
        }
    }

    private class Mobile {
        @JavascriptInterface
        public void onGetWebContentHeight() {
//重新调整webview高度
            mWebView.post(() -> {
                mWebView.measure(0, 0);
                int measuredHeight = mWebView.getMeasuredHeight();
                ViewGroup.LayoutParams lp = mWebView.getLayoutParams();
                lp.height=measuredHeight;
                mWebView.setLayoutParams(lp);
                /*ViewGroup.LayoutParams lp2 = mScrollView.getLayoutParams();
                lp2.height =   mScrollView.getHeight();
                mScrollView.setLayoutParams(lp2);*/
            });


        }
    }
}
